const fs = require("fs");
const path = require("path");
const prettier = require("prettier");
const t = require("../config/dict");
const { error, log } = require("./utils");
const packageTemp = {
  name: "example",
  version: "0.0.1",
  description: "",
  main: "index.js",
  scripts: {
    test: 'echo "Error: no test specified" && exit 1',
  },
  author: "",
  license: "ISC",
};

module.exports = (context, filter) => {
  const dirName = context.metadata.projectDir;
  const filePath = path.resolve(process.cwd(), path.join(".", dirName));
  let fileName = "package",
    activeFile = null,
    isUniapp = false;
  if (context.taskType === "initPackage") {
    activeFile = filePath + "/package.json";
  } else {
    isUniapp = /uniapp/.test(context.metadata.projectType[0].toLowerCase());
    if (
      /vue/.test(context.metadata.projectTechnologyStack.toLowerCase()) &&
      isUniapp
    ) {
      const regex = /vue([0-9]+)/.exec(
        context.metadata.projectTechnologyStack.toLowerCase()
      );
      context.metadata.vueVersion = regex && regex[1] ? regex[1] : "3";
    }
    fileName = !isUniapp ? "package" : "manifest";
    const isStage = /uniapp\(vue[0-9]+,\s*(vite|webpack),\s*/.test(
      context.metadata.projectType[0].toLowerCase()
    );
    //const filePath = path.resolve(process.cwd(), path.join(".", dirName));
    activeFile =
      filePath +
      (!isStage ? "/" : fs.existsSync(filePath + "/src/") ? "/src/" : "/") +
      fileName +
      ".json";
  }
  try {
    if (activeFile && !fs.existsSync(activeFile)) {
      fs.writeFileSync(
        activeFile,
        prettier.format(JSON.stringify(packageTemp), {
          semi: false,
          parser: "json",
        }),
        "utf-8"
      );
    }
    if (activeFile && fs.existsSync(activeFile)) {
      let data = fs.readFileSync(activeFile, "utf-8");
      data = JSON.parse(data);

      if (filter) {
        data = filter(data, { context, isUniapp });
      } else {
        data = {
          ...{
            ...data,
            name: context.metadata.projectName,
            [!isUniapp ? "version" : "versionName"]:
              context.metadata.projectVersion,
            description: context.metadata.projectDescription,
            author: context.metadata.projectAuthor,
          },
        };
        isUniapp && (data.vueVersion = context.metadata.vueVersion);
      }

      fs.writeFileSync(
        activeFile,
        prettier.format(JSON.stringify(data), {
          semi: false,
          parser: "json",
        })
      );
      log("success", {
        message: [
          t(context.lang, "更新"),
          fileName + ".json",
          t(context.lang, "完成"),
          t(context.lang, "。"),
        ].join(" "),
      });
    } else {
      log("error", {
        message: [
          t(context.lang, "更新"),
          fileName + ".json",
          t(context.lang, "失败"),
          t(context.lang, "。"),
        ].join(" "),
      });
    }
    return context;
  } catch (err) {
    log("error", {
      message: [
        t(context.lang, "更新"),
        fileName + ".json",
        t(context.lang, "失败"),
        t(context.lang, "。"),
      ].join(" "),
    });
    error(err);
    return context;
  }
};
